package pub.cleangao.mybatis.meta;

import lombok.Data;
import pub.cleangao.mybatis.cleavage.Cleavage;
import pub.cleangao.mybatis.annotation.Dialect;

import java.io.Serializable;
import java.util.Collections;
import java.util.List;


/**
 * 数据库表的定义
 */
@Data
public class TableDefinition implements Serializable {

    // 数据库名
    String schema;
    // 数据库类型
    Dialect dialect = Dialect.MySQL;
    // 数据源标识
    String dataSourceKey;
    // 表名
    String tableName;
    // 表名标识
    String tableAs;
    // 表注释
    String comment;
    // 字段定义
    List<ColumnDefinition> columnDefinitions = Collections.EMPTY_LIST;
    // 主键列
    ColumnDefinition pkColumn;
    // 乐观锁列
    boolean hasVersion = false;
    ColumnDefinition versionColumn;
    // 逻辑删除列
    boolean hasLogicDelete = false;
    ColumnDefinition logicDeleteColumn;
    // 是否分库或分表
    boolean cleavage;
    // 分库分表策略类
    Class<? extends Cleavage> cleavageClass;
    // 分库分表的参考列
    List<ColumnDefinition> cleavageColumnBy;
    // 二级缓存
    boolean enableCache = true;


    public TableDefinition() {

    }

    public TableDefinition(String tableName) {
        this.tableName = tableName;
    }

    public TableDefinition(String tableName, String tableComment) {
        this.tableName = tableName;
        this.comment = tableComment;
    }


    /**
     * 是否含有时间字段
     *
     * @return true，含有Date类型字段
     */
    public boolean hasDateField() {
        List<ColumnDefinition> columns = getColumnDefinitions();
        for (ColumnDefinition definition : columns) {
            if ("Date".equals(definition.getFieldType())
                    || "LocalDateTime".equals(definition.getFieldType())
                    || "LocalDate".equals(definition.getFieldType())
                    || "Timestamp".equals(definition.getFieldType())) {
                return true;
            }
        }
        return false;
    }

    /**
     * 是否含有BigDecimal字段
     *
     * @return true，含有BigDecimal字段
     */
    public boolean hasBigDecimalField() {
        List<ColumnDefinition> columns = getColumnDefinitions();
        for (ColumnDefinition definition : columns) {
            if ("BigDecimal".equals(definition.getFieldType())) {
                return true;
            }
        }
        return false;
    }

    public boolean getCleavage() {
        return cleavage;
    }

    public boolean isHasVersion() {
        return hasVersion;
    }

    public boolean isHasLogicDelete() {
        return hasLogicDelete;
    }

    public boolean isCleavage() {
        return cleavage;
    }

    public boolean getHasVersion() {
        return hasVersion;
    }

    public boolean getHasLogicDelete() {
        return hasLogicDelete;
    }

    public boolean isEnableCache() {
        return enableCache;
    }

    public boolean getEnableCache() {
        return enableCache;
    }

    public void setEnableCache(boolean enableCache) {
        this.enableCache = enableCache;
    }
}
